<template>
  <div class="tree-select">
    <treeselect
      :options="treeSelectData"
      v-model="defaultValue"
      :always-open="alwaysOpen"
      :defaultExpandLevel="Infinity"
      :searchable="searchable"
      :disable-branch-nodes="disableBranch"
      :openDirection="openDirection"
      :clearable="clearable || true"
      :multiple="isMultiple"
      :maxHeight="400"
      :disabled="disabled"
      :flat="flat"
      :model="model"
      :apiUrl="apiUrl"
      :isLine="isLine"
      :isName="isName"
      :apiData="apiData"
      @select="selectNode"
      :returnType="returnType"
      :placeholder="placeholder"
      :noResultsText="noResultsText"
      :searchPromptText="searchPromptText"
      @input="inputNode"
      @deselect="deselect"
      @close="closeValue"
    />
  </div>
</template>
<script>
// 引用别人做好的轮子 文档：https://vue-treeselect.js.org/#events
import treeselect from '@riophae/vue-treeselect';
import '@riophae/vue-treeselect/dist/vue-treeselect.css';
export default {
  name: 'Treeselect',
  // 由于这组件不支持类型穿透，后期有用到其他api可以自行加
  props: {
    // 当前值
    value: {
      type: String | Number | Array,
    },
    // 树组件数据(外面已经处理好的)
    options: {
      type: Array,
      default: () => [],
    },
    placeholder: {
      type: String,
      default: '请选择',
    },
    //返回类型
    returnType: {
      type: String,
      default: '',
    },
    trigger: {
      type: String,
      default: '',
    },
    noResultsText: {
      type: String,
      default: () => '',
    },
    searchPromptText: {
      type: String,
      default: () => '',
    },
    //校验方法
    normalizerFlag: {
      type: Boolean,
      default: () => false,
    },
    model: {
      type: String,
      default: () => '',
    },
    // 定义树形数据的接口
    apiUrl: {
      type: String,
      default: '',
    },
    // 是否为一行显示
    isLine: {
      type: Boolean,
      default: true,
    },
    // 定义树形数据的参数
    apiData: {
      type: Object,
      default: () => {},
    },
    // 多选
    isMultiple: {
      type: Boolean,
      default: false,
    },
    // 可搜索
    searchable: {
      type: Boolean,
      default: true,
    },
    // 父子节点没有关联，每个节点都是单独的个体
    // 部门树：第一级子节点不可选：isDisabled=true
    flat: {
      type: Boolean,
      default: true,
    },
    // 禁止选择父级
    disableBranch: {
      type: Boolean,
      default: true,
    },
    clearable: {
      type: Boolean,
      default: () => false,
    },
    //是否需要name
    isName: {
      type: Boolean,
      default: () => false,
    },
    disabled: {
      type: Boolean,
      default: () => false,
    },
    openDirection: {
      type: String,
      default: 'auto',
    },
    // 是否打开
    alwaysOpen: {
      type: Boolean,
      default: () => false,
    },
  },
  data() {
    return {
      treeSelectData: this.options.length ? this.options : [],
      defaultValue: this.value ? this.value : null,
    };
  },
  created() {
    if (this.apiUrl) {
      this.initDepartment();
    }
  },
  methods: {
    initDepartment() {
      try {
        // 后期要与后端约定
        this.$axios.post(this.apiUrl, this.apiData).then((res) => {
          if (0 == res.data.code) {
            this.treeSelectData = res.data.data;
            // 返回的数据必须是树形的，如果不是还得在这加逻辑，可以和后端对齐
            this.getSelectedNode(this.treeSelectData, this.treeSelectData);
          } else {
            this.$alert(res.data.msg);
          }
        });
      } catch (e) {
        console.log(e);
      }
    },
    //删掉没有子节点的children
    getSelectedNode(nodeData) {
      nodeData.forEach((item) => {
        if ('children' in item && item.children.length === 0) {
          delete item.children;
        } else if ('children' in item && item.children.length) {
          this.getSelectedNode(item.children, item);
        }
      });
    },
    inputNode(value) {
      if (this.isMultiple) {
        // 多选，返回字符串  统一返回字符串，不用数组
        console.log(value);
        let val = value.join(',') == '' ? null : value.join(',');
        this.$emit('setSearchModal', this.model, val);
      }
    },
    deselect(val) {
      console.log('deselect', val);
    },
    closeValue(val) {
      console.log('closeValue', val);
      this.$emit('input', val);
    },
    //清空
    clearableValue() {
      this.$emit('setSearchModal', this.model, null);
    },
    selectNode(node) {
      console.log(node);
      if (!this.isMultiple) {
        if (this.returnType == '') {
          this.$emit('setSearchModal', this.model, this.isName ? node.label : node.id);
        } else {
          this.$emit('setSearchModal', this.model, node);
        }
      }
    },
  },
  watch: {
    //清空
    defaultValue(value) {
      if (value == undefined) {
        this.clearableValue();
      }
    },
    currentValue(newValue) {
      this.defaultValue = newValue || null;
    },
  },
  components: { treeselect },
};
</script>
<style lang="scss" scoped>
.tree-select {
  ::v-deep .vue-treeselect__control {
    height: 32px;
    line-height: 32px;
  }
  ::v-deep .vue-treeselect__multi-value {
    overflow: hidden !important;
    text-overflow: ellipsis !important;
    white-space: nowrap !important;
    width: 100% !important;
    height: 100% !important;
  }

  ::v-deep .vue-treeselect__control {
    display: flex;
    align-items: center;
  }
}
</style>
